package com.bookmanagement.service.impl;

import com.bookmanagement.DTO.PasswordUpdateDTO;
import com.bookmanagement.DTO.UserAccountDTO;
import com.bookmanagement.DTO.UserUpdateDTO;
import com.bookmanagement.VO.AdminUserVO;
import com.bookmanagement.VO.UserVO;
import com.bookmanagement.constant.AccountExceptionConstant;
import com.bookmanagement.entity.User;
import com.bookmanagement.exception.BusinessException;
import com.bookmanagement.mapper.UserMapper;
import com.bookmanagement.mq.UserRegisterProducer;
import com.bookmanagement.service.UserService;
import com.bookmanagement.utils.BaseContext;
import com.bookmanagement.utils.BcryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author skyjay
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserRegisterProducer userRegisterProducer;
    @Override
    public User login(UserAccountDTO userAccountDTO) {
        User user = userMapper.queryByEmail(userAccountDTO.getEmail());
        if (user == null) {
            throw new BusinessException(AccountExceptionConstant.USER_NOT_EXIST);
        }

        if (!BcryptUtil.checkPassword(userAccountDTO.getPassword(), user.getPassword())) {
            throw new BusinessException(AccountExceptionConstant.USER_PASSWORD_ERROR);
        }

        return user;
    }

    @Override
    public void register(UserAccountDTO userAccountDTO) {
        // 检查用户是否已存在
        User user = userMapper.queryByEmail(userAccountDTO.getEmail());
        if (user != null) {
            throw new BusinessException(AccountExceptionConstant.USER_EXIST);
        }
        
        // 发送注册消息到MQ，异步处理
        userRegisterProducer.sendRegisterMessage(userAccountDTO);
    }

    @Override
    public UserVO getInfo() {
        String email = BaseContext.getCurrentId();
        User user = userMapper.queryByEmail(email);
        return UserVO.builder()
                .username(user.getUsername())
                .avatar(user.getAvatar())
                .isAdmin(user.getIsAdmin())
                .status(user.getStatus())
                .build();
    }

    @Override
    public void updateUserInfo(UserUpdateDTO userUpdateDTO) {
        String email = BaseContext.getCurrentId();
        User user = userMapper.queryByEmail(email);
        if (user == null) {
            throw new BusinessException(AccountExceptionConstant.USER_NOT_EXIST);
        }
        
        // 更新用户信息（只更新非空字段）
        if (userUpdateDTO.getUsername() != null) {
            user.setUsername(userUpdateDTO.getUsername());
        }
        if (userUpdateDTO.getAvatar() != null) {
            user.setAvatar(userUpdateDTO.getAvatar());
        }
        userMapper.updateUserInfo(user);
    }

    @Override
    public void updatePassword(PasswordUpdateDTO passwordUpdateDTO) {
        String email = BaseContext.getCurrentId();
        User user = userMapper.queryByEmail(email);
        if (user == null) {
            throw new BusinessException(AccountExceptionConstant.USER_NOT_EXIST);
        }
        
        // 验证旧密码
        if (!BcryptUtil.checkPassword(passwordUpdateDTO.getOldPassword(), user.getPassword())) {
            throw new BusinessException(AccountExceptionConstant.USER_PASSWORD_ERROR);
        }
        
        // 加密新密码并更新
        user.setPassword(BcryptUtil.encrypt(passwordUpdateDTO.getNewPassword()));
        userMapper.updatePassword(user);
    }

    @Override
    public void toggleUserStatus(Integer userId) {
        User user = userMapper.queryById(userId);
        if (user == null) {
            throw new BusinessException(AccountExceptionConstant.USER_NOT_EXIST);
        }
        
        // 切换状态：如果当前是启用(true)，则禁用(false)；反之亦然
        Boolean newStatus = !user.getStatus();
        userMapper.updateUserStatus(userId, newStatus);
    }

    @Override
    public void resetUserPassword(Integer userId) {
        User user = userMapper.queryById(userId);
        if (user == null) {
            throw new BusinessException(AccountExceptionConstant.USER_NOT_EXIST);
        }
        
        // 重置密码为123456，使用BCrypt加密后存储
        String defaultPassword = "123456";
        String encryptedPassword = BcryptUtil.encrypt(defaultPassword);
        userMapper.resetPassword(userId, encryptedPassword);
    }

    @Override
    public List<AdminUserVO> getAllUsers() {
        List<User> users = userMapper.getAllUsers();
        // 转换为AdminUserVO，过滤掉isAdmin字段
        return users.stream().map(user -> AdminUserVO.builder()
                .id(user.getId())
                .email(user.getEmail())
                .password(user.getPassword())
                .username(user.getUsername())
                .avatar(user.getAvatar())
                .status(user.getStatus())
                .createAt(user.getCreateAt())
                .updateAt(user.getUpdateAt())
                .build()
        ).collect(Collectors.toList());
    }
}
